<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>智能拍卖系统</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
  <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.8/dist/chart.umd.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/web3@1.8.2/dist/web3.min.js"></script>
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
  
  <script>
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            primary: '#165DFF',
            secondary: '#0D2B99',
            accent: '#6E56CF',
            dark: '#0A1929',
            light: '#E0E7FF',
            success: '#00C853',
            warning: '#FF9800',
            danger: '#F44336',
            info: '#2196F3'
          },
          fontFamily: {
            inter: ['Inter', 'sans-serif'],
          },
        },
      }
    }
  </script>
  
  <style type="text/tailwindcss">
    @layer utilities {
      .content-auto {
        content-visibility: auto;
      }
      .text-shadow {
        text-shadow: 0 0 8px rgba(22, 93, 255, 0.5);
      }
      .glow {
        box-shadow: 0 0 15px rgba(22, 93, 255, 0.5);
      }
      .bg-grid {
        background-image: 
          linear-gradient(rgba(22, 93, 255, 0.05) 1px, transparent 1px),
          linear-gradient(90deg, rgba(22, 93, 255, 0.05) 1px, transparent 1px);
        background-size: 20px 20px;
      }
      .glass {
        background: rgba(10, 25, 41, 0.7);
        backdrop-filter: blur(10px);
        -webkit-backdrop-filter: blur(10px);
      }
      .animate-pulse-slow {
        animation: pulse 3s cubic-bezier(0.4, 0, 0.6, 1) infinite;
      }
      .animate-float {
        animation: float 6s ease-in-out infinite;
      }
      @keyframes float {
        0% { transform: translateY(0px); }
        50% { transform: translateY(-10px); }
        100% { transform: translateY(0px); }
      }
    }
  </style>
</head>
<body class="bg-dark text-light font-inter min-h-screen flex flex-col bg-grid">
  <!-- 顶部导航栏 -->
  <header class="glass border-b border-primary/20 sticky top-0 z-50 transition-all duration-300">
    <div class="container mx-auto px-4 py-3 flex justify-between items-center">
      <div class="flex items-center space-x-2">
        <div class="text-primary text-3xl">
          <i class="fa fa-gavel animate-pulse-slow"></i>
        </div>
        <h1 class="text-xl md:text-2xl font-bold text-shadow">智能拍卖系统</h1>
      </div>
      
      <div class="flex items-center space-x-4">
        <div id="connectionStatus" class="text-sm hidden md:block">
          <span class="inline-block w-2 h-2 rounded-full bg-danger mr-1"></span>
          <span>未连接钱包</span>
        </div>
        <button id="connectWalletBtn" class="bg-primary hover:bg-primary/90 text-white px-4 py-2 rounded-lg transition-all duration-300 transform hover:scale-105 flex items-center space-x-2">
          <i class="fa fa-wallet"></i>
          <span>连接钱包</span>
        </button>
      </div>
    </div>
  </header>

  <!-- 主内容区 -->
  <main class="flex-grow container mx-auto px-4 py-8">
    <!-- 合约配置区 -->
    <section id="contractSetup" class="mb-8 glass rounded-xl p-6 border border-primary/30 transition-all duration-300 hover:glow">
      <h2 class="text-xl font-semibold mb-4 flex items-center">
        <i class="fa fa-cogs text-primary mr-2"></i>
        合约配置
      </h2>
      
      <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div>
          <label class="block text-sm font-medium mb-1">合约地址</label>
          <div class="relative">
            <input id="contractAddress" type="text" class="w-full bg-dark/80 border border-primary/40 rounded-lg px-4 py-2 focus:outline-none focus:ring-2 focus:ring-primary/50" placeholder="0x..." value="">
            <button id="loadContractBtn" class="absolute right-1 top-1 bg-primary text-white px-3 py-1 rounded-md text-sm hover:bg-primary/90 transition-all">
              加载合约
            </button>
          </div>
        </div>
        
        <div>
          <label class="block text-sm font-medium mb-1">ABI (JSON格式)</label>
          <textarea id="contractABI" rows="4" class="w-full bg-dark/80 border border-primary/40 rounded-lg px-4 py-2 focus:outline-none focus:ring-2 focus:ring-primary/50" placeholder='[{"inputs":...}]' style="font-family: monospace;"></textarea>
        </div>
      </div>
      
      <div class="mt-4 text-sm text-gray-400">
        <p>提示：请在上方输入拍卖合约地址和ABI。ABI可从Solidity编译器输出中获取。</p>
      </div>
    </section>

    <!-- 拍卖信息展示 -->
    <section id="auctionInfo" class="mb-8 glass rounded-xl p-6 border border-primary/30 transition-all duration-300 hover:glow">
      <h2 class="text-xl font-semibold mb-4 flex items-center">
        <i class="fa fa-info-circle text-primary mr-2"></i>
        拍卖信息
      </h2>
      
      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
        <div class="bg-dark/50 p-4 rounded-lg border border-primary/20">
          <p class="text-xs text-gray-400 mb-1">拍卖状态</p>
          <p id="auctionState" class="text-lg font-semibold">-</p>
        </div>
        
        <div class="bg-dark/50 p-4 rounded-lg border border-primary/20">
          <p class="text-xs text-gray-400 mb-1">当前最高出价</p>
          <p id="highestBid" class="text-lg font-semibold">-</p>
        </div>
        
        <div class="bg-dark/50 p-4 rounded-lg border border-primary/20">
          <p class="text-xs text-gray-400 mb-1">最高出价者</p>
          <p id="highestBidder" class="text-lg font-semibold truncate">-</p>
        </div>
        
        <div class="bg-dark/50 p-4 rounded-lg border border-primary/20">
          <p class="text-xs text-gray-400 mb-1">拍卖结束时间</p>
          <p id="auctionEndTime" class="text-lg font-semibold">-</p>
        </div>
      </div>
      
      <div class="mt-4 bg-dark/50 p-4 rounded-lg border border-primary/20">
        <p class="text-xs text-gray-400 mb-1">拍卖物品</p>
        <p id="auctionItem" class="text-lg font-semibold">-</p>
      </div>
      
      <div class="mt-4 grid grid-cols-1 md:grid-cols-2 gap-4">
        <div class="bg-dark/50 p-4 rounded-lg border border-primary/20">
          <p class="text-xs text-gray-400 mb-1">保证金金额</p>
          <p id="depositAmount" class="text-lg font-semibold">-</p>
        </div>
        
        <div class="bg-dark/50 p-4 rounded-lg border border-primary/20">
          <p class="text-xs text-gray-400 mb-1">最低出价</p>
          <p id="minimumBid" class="text-lg font-semibold">-</p>
        </div>
      </div>
    </section>

    <!-- 操作按钮区域 -->
    <section id="actions" class="mb-8 glass rounded-xl p-6 border border-primary/30 transition-all duration-300 hover:glow">
      <h2 class="text-xl font-semibold mb-4 flex items-center">
        <i class="fa fa-terminal text-primary mr-2"></i>
        拍卖操作
      </h2>
      
      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        <!-- 受益人操作 -->
        <div class="bg-dark/50 p-4 rounded-lg border border-primary/20">
          <h3 class="text-md font-semibold mb-3 text-primary">受益人操作</h3>
          
          <div class="space-y-3">
            <button id="startAuctionBtn" class="w-full bg-primary hover:bg-primary/90 text-white px-4 py-2 rounded-lg transition-all duration-300 transform hover:scale-105 flex items-center justify-center space-x-2">
              <i class="fa fa-play"></i>
              <span>开始拍卖</span>
            </button>
            
            <button id="cancelAuctionBtn" class="w-full bg-danger hover:bg-danger/90 text-white px-4 py-2 rounded-lg transition-all duration-300 transform hover:scale-105 flex items-center justify-center space-x-2">
              <i class="fa fa-times"></i>
              <span>取消拍卖</span>
            </button>
            
            <button id="endAuctionBtn" class="w-full bg-warning hover:bg-warning/90 text-white px-4 py-2 rounded-lg transition-all duration-300 transform hover:scale-105 flex items-center justify-center space-x-2">
              <i class="fa fa-flag"></i>
              <span>结束拍卖</span>
            </button>
          </div>
        </div>
        
        <!-- 参与者操作 -->
        <div class="bg-dark/50 p-4 rounded-lg border border-primary/20">
          <h3 class="text-md font-semibold mb-3 text-primary">参与者操作</h3>
          
          <div class="space-y-3">
            <button id="payDepositBtn" class="w-full bg-accent hover:bg-accent/90 text-white px-4 py-2 rounded-lg transition-all duration-300 transform hover:scale-105 flex items-center justify-center space-x-2">
              <i class="fa fa-lock"></i>
              <span>支付保证金</span>
            </button>
            
            <div class="relative">
              <input id="bidAmount" type="number" min="0" step="0.0000000001" class="w-full bg-dark/80 border border-primary/40 rounded-lg px-4 py-2 focus:outline-none focus:ring-2 focus:ring-primary/50" placeholder="输入出价金额">
              <button id="bidBtn" class="absolute right-1 top-1 bg-success hover:bg-success/90 text-white px-3 py-1 rounded-md text-sm transition-all">
                <i class="fa fa-gavel"></i> 出价
              </button>
            </div>
            
            <button id="withdrawBtn" class="w-full bg-info hover:bg-info/90 text-white px-4 py-2 rounded-lg transition-all duration-300 transform hover:scale-105 flex items-center justify-center space-x-2">
              <i class="fa fa-refresh"></i>
              <span>提取退款</span>
            </button>
            
            <button id="refundWinnerDepositBtn" class="w-full bg-info hover:bg-info/90 text-white px-4 py-2 rounded-lg transition-all duration-300 transform hover:scale-105 flex items-center justify-center space-x-2">
              <i class="fa fa-unlock"></i>
              <span>退还中标保证金</span>
            </button>
          </div>
        </div>
        
        <!-- 信息查询 -->
        <div class="bg-dark/50 p-4 rounded-lg border border-primary/20">
          <h3 class="text-md font-semibold mb-3 text-primary">信息查询</h3>
          
          <div class="space-y-3">
            <div class="relative">
              <input id="checkAddress" type="text" class="w-full bg-dark/80 border border-primary/40 rounded-lg px-4 py-2 focus:outline-none focus:ring-2 focus:ring-primary/50" placeholder="输入地址查询出价和保证金">
              <button id="checkBidBtn" class="absolute right-1 top-1 bg-primary hover:bg-primary/90 text-white px-3 py-1 rounded-md text-sm transition-all">
                <i class="fa fa-search"></i> 查询
              </button>
            </div>
            
            <div id="bidInfoResult" class="mt-2 p-3 bg-dark/80 border border-primary/20 rounded-lg text-sm hidden">
              <p><span class="text-gray-400">地址:</span> <span id="resultAddress">-</span></p>
              <p><span class="text-gray-400">当前出价:</span> <span id="resultBidAmount">-</span></p>
              <p><span class="text-gray-400">保证金状态:</span> <span id="resultDepositStatus">-</span></p>
            </div>
            
            <button id="verifySignatureBtn" class="w-full bg-secondary hover:bg-secondary/90 text-white px-4 py-2 rounded-lg transition-all duration-300 transform hover:scale-105 flex items-center justify-center space-x-2">
              <i class="fa fa-shield"></i>
              <span>验证签名</span>
            </button>
          </div>
        </div>
      </div>
    </section>

    <!-- 拍卖历史和统计 -->
    <section id="history" class="glass rounded-xl p-6 border border-primary/30 transition-all duration-300 hover:glow">
      <h2 class="text-xl font-semibold mb-4 flex items-center">
        <i class="fa fa-history text-primary mr-2"></i>
        拍卖历史
      </h2>
      
      <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <div class="lg:col-span-2">
          <div class="bg-dark/50 p-4 rounded-lg border border-primary/20 h-full">
            <h3 class="text-md font-semibold mb-3">出价记录</h3>
            <div id="bidHistory" class="space-y-2 max-h-[300px] overflow-y-auto pr-2">
              <!-- 出价记录将在这里动态生成 -->
              <div class="text-center text-gray-400 py-8">
                <i class="fa fa-hourglass-half text-3xl mb-2 block"></i>
                <p>暂无出价记录</p>
              </div>
            </div>
          </div>
        </div>
        
        <div>
          <div class="bg-dark/50 p-4 rounded-lg border border-primary/20 h-full">
            <h3 class="text-md font-semibold mb-3">拍卖统计</h3>
            <div class="h-[250px]">
              <canvas id="bidChart"></canvas>
            </div>
          </div>
        </div>
      </div>
    </section>
  </main>

  <!-- 页脚 -->
  <footer class="glass border-t border-primary/20 py-4">
    <div class="container mx-auto px-4 text-center text-sm text-gray-400">
      <p>智能拍卖系统 &copy; 2025 | 基于以太坊区块链</p>
    </div>
  </footer>

  <!-- 模态框 -->
  <div id="modal" class="fixed inset-0 bg-black/70 flex items-center justify-center z-50 hidden">
    <div class="bg-dark max-w-md w-full rounded-xl p-6 border border-primary/30 relative transform transition-all duration-300 scale-95 opacity-0" id="modalContent">
      <button id="closeModalBtn" class="absolute top-3 right-3 text-gray-400 hover:text-white">
        <i class="fa fa-times"></i>
      </button>
      
      <h3 id="modalTitle" class="text-xl font-semibold mb-4"></h3>
      
      <div id="modalBody" class="mb-4"></div>
      
      <div class="flex justify-end space-x-3">
        <button id="modalCancelBtn" class="px-4 py-2 border border-gray-600 rounded-lg hover:bg-gray-800 transition-all">
          取消
        </button>
        <button id="modalConfirmBtn" class="px-4 py-2 bg-primary hover:bg-primary/90 text-white rounded-lg transition-all">
          确认
        </button>
      </div>
    </div>
  </div>

  <!-- 通知提示 -->
  <div id="notification" class="fixed bottom-4 right-4 max-w-md w-full z-50 transform translate-y-20 opacity-0 transition-all duration-500"></div>

  <script>
    // 全局变量
    let web3;
    let contract;
    let contractAddress = '';
    let contractABI = '';
    let currentAccount = null;
    let bidHistory = [];
    
    // DOM元素
    const connectWalletBtn = document.getElementById('connectWalletBtn');
    const connectionStatus = document.getElementById('connectionStatus');
    const contractAddressInput = document.getElementById('contractAddress');
    const contractABIInput = document.getElementById('contractABI');
    const loadContractBtn = document.getElementById('loadContractBtn');
    const bidChart = document.getElementById('bidChart');
    const notification = document.getElementById('notification');
    
    // 模态框元素
    const modal = document.getElementById('modal');
    const modalContent = document.getElementById('modalContent');
    const modalTitle = document.getElementById('modalTitle');
    const modalBody = document.getElementById('modalBody');
    const closeModalBtn = document.getElementById('closeModalBtn');
    const modalCancelBtn = document.getElementById('modalCancelBtn');
    const modalConfirmBtn = document.getElementById('modalConfirmBtn');
    
    // 图表初始化
    const chart = new Chart(bidChart, {
      type: 'line',
      data: {
        labels: [],
        datasets: [{
          label: '出价金额 (ETH)',
          data: [],
          borderColor: '#165DFF',
          backgroundColor: 'rgba(22, 93, 255, 0.1)',
          borderWidth: 2,
          tension: 0.3,
          fill: true
        }]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        scales: {
          x: {
            grid: {
              color: 'rgba(22, 93, 255, 0.1)'
            },
            ticks: {
              color: '#E0E7FF'
            }
          },
          y: {
            grid: {
              color: 'rgba(22, 93, 255, 0.1)'
            },
            ticks: {
              color: '#E0E7FF'
            }
          }
        },
        plugins: {
          legend: {
            labels: {
              color: '#E0E7FF'
            }
          }
        }
      }
    });
    
    // 初始化函数
    async function init() {
      // 检查是否有MetaMask
      if (typeof window.ethereum !== 'undefined') {
        web3 = new Web3(window.ethereum);
        
        // 监听账户变化
        window.ethereum.on('accountsChanged', (accounts) => {
          if (accounts.length > 0) {
            currentAccount = accounts[0];
            updateUI();
          } else {
            currentAccount = null;
            updateUI();
            showNotification('warning', '钱包已断开连接');
          }
        });
        
        // 监听网络变化
        window.ethereum.on('chainChanged', () => {
          window.location.reload();
        });
      } else {
        showNotification('error', '请安装MetaMask钱包以使用此应用');
        connectWalletBtn.disabled = true;
      }
      
      // 设置事件监听器
      setupEventListeners();
    }
    
    // 设置事件监听器
    function setupEventListeners() {
      // 连接钱包按钮
      connectWalletBtn.addEventListener('click', connectWallet);
      
      // 加载合约按钮
      loadContractBtn.addEventListener('click', loadContract);
      
      // 拍卖操作按钮
      document.getElementById('startAuctionBtn').addEventListener('click', startAuction);
      document.getElementById('cancelAuctionBtn').addEventListener('click', cancelAuction);
      document.getElementById('endAuctionBtn').addEventListener('click', endAuction);
      document.getElementById('payDepositBtn').addEventListener('click', payDeposit);
      document.getElementById('bidBtn').addEventListener('click', placeBid);
      document.getElementById('withdrawBtn').addEventListener('click', withdraw);
      document.getElementById('refundWinnerDepositBtn').addEventListener('click', refundWinnerDeposit);
      document.getElementById('checkBidBtn').addEventListener('click', checkBidInfo);
      document.getElementById('verifySignatureBtn').addEventListener('click', verifySignature);
      
      // 模态框按钮
      closeModalBtn.addEventListener('click', closeModal);
      modalCancelBtn.addEventListener('click', closeModal);
      
      // 滚动效果
      window.addEventListener('scroll', () => {
        const header = document.querySelector('header');
        if (window.scrollY > 10) {
          header.classList.add('py-2');
          header.classList.remove('py-3');
        } else {
          header.classList.add('py-3');
          header.classList.remove('py-2');
        }
      });
    }
    
    // 连接钱包
    async function connectWallet() {
      try {
        const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
        currentAccount = accounts[0];
        updateUI();
        showNotification('success', '钱包连接成功');
      } catch (error) {
        console.error('连接钱包失败:', error);
        showNotification('error', '连接钱包失败: ' + error.message);
      }
    }
    
    // 加载合约
    async function loadContract() {
      contractAddress = contractAddressInput.value.trim();
      contractABI = contractABIInput.value.trim();
      
      if (!contractAddress || !contractABI) {
        showNotification('error', '请输入合约地址和ABI');
        return;
      }
      
      try {
        // 解析ABI
        const parsedABI = JSON.parse(contractABI);
        
        // 创建合约实例
        contract = new web3.eth.Contract(parsedABI, contractAddress);
        
        // 更新UI
        updateAuctionInfo();
        updateBidHistory();
        showNotification('success', '合约加载成功');
        
        // 监听合约事件
        setupContractEventListeners();
      } catch (error) {
        console.error('加载合约失败:', error);
        showNotification('error', '加载合约失败: ' + error.message);
      }
    }
    
    // 设置合约事件监听器
    function setupContractEventListeners() {
      if (!contract) return;
      
      // 监听最高出价增加事件
      contract.events.HighestBidIncreased({ fromBlock: 'latest' })
        .on('data', (event) => {
          updateAuctionInfo();
          updateBidHistory();
          showNotification('info', `新的最高出价: ${web3.utils.fromWei(event.returnValues.amount, 'ether')} ETH`);
        })
        .on('error', (error) => {
          console.error('监听HighestBidIncreased事件失败:', error);
        });
      
      // 监听拍卖结束事件
      contract.events.AuctionEnded({ fromBlock: 'latest' })
        .on('data', (event) => {
          updateAuctionInfo();
          showNotification('info', `拍卖已结束，中标者: ${event.returnValues.winner}`);
        })
        .on('error', (error) => {
          console.error('监听AuctionEnded事件失败:', error);
        });
      
      // 监听保证金支付事件
      contract.events.DepositPaid({ fromBlock: 'latest' })
        .on('data', (event) => {
          updateAuctionInfo();
          showNotification('info', `${event.returnValues.bidder} 已支付保证金`);
        })
        .on('error', (error) => {
          console.error('监听DepositPaid事件失败:', error);
        });
      
      // 监听保证金退还事件
      contract.events.DepositRefunded({ fromBlock: 'latest' })
        .on('data', (event) => {
          updateAuctionInfo();
          showNotification('info', `${event.returnValues.bidder} 已退还保证金`);
        })
        .on('error', (error) => {
          console.error('监听DepositRefunded事件失败:', error);
        });
    }
    
    // 更新UI
    function updateUI() {
      // 更新连接状态
      if (currentAccount) {
        connectionStatus.innerHTML = `
          <span class="inline-block w-2 h-2 rounded-full bg-success mr-1"></span>
          <span>已连接: ${currentAccount.substring(0, 6)}...${currentAccount.substring(currentAccount.length - 4)}</span>
        `;
        connectWalletBtn.innerHTML = '<i class="fa fa-check"></i> <span>已连接</span>';
        connectWalletBtn.classList.remove('bg-primary');
        connectWalletBtn.classList.add('bg-success');
      } else {
        connectionStatus.innerHTML = `
          <span class="inline-block w-2 h-2 rounded-full bg-danger mr-1"></span>
          <span>未连接钱包</span>
        `;
        connectWalletBtn.innerHTML = '<i class="fa fa-wallet"></i> <span>连接钱包</span>';
        connectWalletBtn.classList.remove('bg-success');
        connectWalletBtn.classList.add('bg-primary');
      }
      
      // 启用/禁用按钮
      const walletConnected = currentAccount !== null;
      const contractLoaded = contract !== null;
      
      document.getElementById('startAuctionBtn').disabled = !(walletConnected && contractLoaded);
      document.getElementById('cancelAuctionBtn').disabled = !(walletConnected && contractLoaded);
      document.getElementById('endAuctionBtn').disabled = !(walletConnected && contractLoaded);
      document.getElementById('payDepositBtn').disabled = !(walletConnected && contractLoaded);
      document.getElementById('bidBtn').disabled = !(walletConnected && contractLoaded);
      document.getElementById('withdrawBtn').disabled = !(walletConnected && contractLoaded);
      document.getElementById('refundWinnerDepositBtn').disabled = !(walletConnected && contractLoaded);
      document.getElementById('checkBidBtn').disabled = !(walletConnected && contractLoaded);
      document.getElementById('verifySignatureBtn').disabled = !(walletConnected && contractLoaded);
    }
    
    // 更新拍卖信息
    async function updateAuctionInfo() {
      if (!contract) return;
      
      try {
        // 获取拍卖信息
        const auction = await contract.methods.auction().call();
        
        // 更新UI
        document.getElementById('auctionItem').textContent = auction.item;
        document.getElementById('highestBid').textContent = `${web3.utils.fromWei(auction.highestBid, 'ether')} ETH`;
        document.getElementById('highestBidder').textContent = auction.highestBidder || '-';
        document.getElementById('depositAmount').textContent = `${web3.utils.fromWei(auction.depositAmount, 'ether')} ETH`;
        document.getElementById('minimumBid').textContent = `${web3.utils.fromWei(auction.minimumBid, 'ether')} ETH`;
        
        // 格式化拍卖结束时间
        const endTime = new Date(auction.auctionEnd * 1000);
        document.getElementById('auctionEndTime').textContent = endTime.toLocaleString();
        
        // 更新拍卖状态
        const state = parseInt(auction.state);
        let stateText = '';
        let stateColor = '';
        
        switch (state) {
          case 0: // Created
            stateText = '已创建';
            stateColor = 'text-info';
            break;
          case 1: // Started
            stateText = '进行中';
            stateColor = 'text-success';
            break;
          case 2: // Ended
            stateText = '已结束';
            stateColor = 'text-warning';
            break;
          case 3: // Canceled
            stateText = '已取消';
            stateColor = 'text-danger';
            break;
          default:
            stateText = '未知状态';
            stateColor = 'text-gray-400';
        }
        
        document.getElementById('auctionState').textContent = stateText;
        document.getElementById('auctionState').className = `text-lg font-semibold ${stateColor}`;
        
        // 更新图表
        updateChart();
      } catch (error) {
        console.error('获取拍卖信息失败:', error);
        showNotification('error', '获取拍卖信息失败: ' + error.message);
      }
    }
    
    // 更新出价历史
    async function updateBidHistory() {
      if (!contract) return;
      
      try {
        // 清空历史
        document.getElementById('bidHistory').innerHTML = '';
        
        // 获取历史事件
        const events = await contract.getPastEvents('HighestBidIncreased', {
          fromBlock: 0,
          toBlock: 'latest'
        });
        
        bidHistory = events.map(event => ({
          bidder: event.returnValues.bidder,
          amount: event.returnValues.amount,
          timestamp: event.blockTimestamp || 0
        }));
        
        // 按时间排序
        bidHistory.sort((a, b) => b.timestamp - a.timestamp);
        
        // 显示历史
        if (bidHistory.length > 0) {
          bidHistory.forEach(bid => {
            const bidElement = document.createElement('div');
            bidElement.className = 'bg-dark/70 p-3 rounded-lg border border-primary/10 hover:border-primary/30 transition-all';
            bidElement.innerHTML = `
              <div class="flex justify-between items-center">
                <div>
                  <p class="font-medium">${bid.bidder.substring(0, 8)}...</p>
                  <p class="text-xs text-gray-400">${new Date(bid.timestamp * 1000).toLocaleString()}</p>
                </div>
                <div class="text-right">
                  <p class="font-semibold">${web3.utils.fromWei(bid.amount, 'ether')} ETH</p>
                  <p class="text-xs text-gray-400">最高出价</p>
                </div>
              </div>
            `;
            document.getElementById('bidHistory').appendChild(bidElement);
          });
        } else {
          document.getElementById('bidHistory').innerHTML = `
            <div class="text-center text-gray-400 py-8">
              <i class="fa fa-hourglass-half text-3xl mb-2 block"></i>
              <p>暂无出价记录</p>
            </div>
          `;
        }
      } catch (error) {
        console.error('获取出价历史失败:', error);
        showNotification('error', '获取出价历史失败: ' + error.message);
      }
    }
    
    // 更新图表
    function updateChart() {
      if (bidHistory.length === 0) return;
      
      // 准备图表数据
      const sortedBids = [...bidHistory].sort((a, b) => a.timestamp - b.timestamp);
      const labels = sortedBids.map(bid => 
        new Date(bid.timestamp * 1000).toLocaleTimeString()
      );
      const data = sortedBids.map(bid => 
        parseFloat(web3.utils.fromWei(bid.amount, 'ether'))
      );
      
      // 更新图表
      chart.data.labels = labels;
      chart.data.datasets[0].data = data;
      chart.update();
    }
    
    // 开始拍卖
    function startAuction() {
      showConfirmationModal(
        '开始拍卖',
        '确定要开始拍卖吗？此操作将启动拍卖流程，参与者可以开始出价。',
        async () => {
          try {
            await contract.methods.startAuction().send({ from: currentAccount });
            showNotification('success', '拍卖已成功开始');
            updateAuctionInfo();
          } catch (error) {
            console.error('开始拍卖失败:', error);
            showNotification('error', '开始拍卖失败: ' + error.message);
          }
        }
      );
    }
    
    // 取消拍卖
    function cancelAuction() {
      showConfirmationModal(
        '取消拍卖',
        '确定要取消拍卖吗？此操作将终止拍卖流程，所有参与者将能够取回保证金。',
        async () => {
          try {
            await contract.methods.cancelAuction().send({ from: currentAccount });
            showNotification('success', '拍卖已成功取消');
            updateAuctionInfo();
          } catch (error) {
            console.error('取消拍卖失败:', error);
            showNotification('error', '取消拍卖失败: ' + error.message);
          }
        }
      );
    }
    
    // 结束拍卖
    function endAuction() {
      showConfirmationModal(
        '结束拍卖',
        '确定要结束拍卖吗？此操作将结束拍卖流程，最高出价者将赢得拍卖。',
        async () => {
          try {
            await contract.methods.auctionEnd().send({ from: currentAccount });
            showNotification('success', '拍卖已成功结束');
            updateAuctionInfo();
          } catch (error) {
            console.error('结束拍卖失败:', error);
            showNotification('error', '结束拍卖失败: ' + error.message);
          }
        }
      );
    }
    
    // 支付保证金
    function payDeposit() {
      showConfirmationModal(
        '支付保证金',
        '确定要支付保证金吗？此操作将锁定您的资金作为参与拍卖的保证金。',
        async () => {
          try {
            const auction = await contract.methods.auction().call();
            const depositAmount = auction.depositAmount;
            
            await contract.methods.payDeposit().send({
              from: currentAccount,
              value: depositAmount
            });
            
            showNotification('success', '保证金支付成功');
            updateAuctionInfo();
          } catch (error) {
            console.error('支付保证金失败:', error);
            showNotification('error', '支付保证金失败: ' + error.message);
          }
        }
      );
    }
    
    // 出价
    function placeBid() {
      const bidAmount = document.getElementById('bidAmount').value.trim();
      
      if (!bidAmount || parseFloat(bidAmount) <= 0) {
        showNotification('error', '请输入有效的出价金额');
        return;
      }
      
      showConfirmationModal(
        '提交出价',
        `确定要出价 ${bidAmount} ETH 吗？此金额必须大于当前最高出价和最低出价要求。`,
        async () => {
          try {
            const weiAmount = web3.utils.toWei(bidAmount, 'ether');
            
            await contract.methods.bid().send({
              from: currentAccount,
              value: weiAmount
            });
            
            showNotification('success', '出价成功');
            document.getElementById('bidAmount').value = '';
            updateAuctionInfo();
            updateBidHistory();
          } catch (error) {
            console.error('出价失败:', error);
            showNotification('error', '出价失败: ' + error.message);
          }
        }
      );
    }
    
    // 提取退款
    function withdraw() {
      showConfirmationModal(
        '提取退款',
        '确定要提取退款吗？此操作将返还您的未中标金额和保证金（如果适用）。',
        async () => {
          try {
            await contract.methods.withdraw().send({ from: currentAccount });
            showNotification('success', '退款提取成功');
            updateAuctionInfo();
          } catch (error) {
            console.error('提取退款失败:', error);
            showNotification('error', '提取退款失败: ' + error.message);
          }
        }
      );
    }
    
    // 退还中标者保证金
    function refundWinnerDeposit() {
      showConfirmationModal(
        '退还中标保证金',
        '确定要退还中标保证金吗？此操作仅适用于中标者，且拍卖必须已结束。',
        async () => {
          try {
            await contract.methods.refundWinnerDeposit().send({ from: currentAccount });
            showNotification('success', '中标保证金退还成功');
            updateAuctionInfo();
          } catch (error) {
            console.error('退还中标保证金失败:', error);
            showNotification('error', '退还中标保证金失败: ' + error.message);
          }
        }
      );
    }
    
    // 查询出价信息
    async function checkBidInfo() {
      const address = document.getElementById('checkAddress').value.trim();
      
      if (!web3.utils.isAddress(address)) {
        showNotification('error', '请输入有效的以太坊地址');
        return;
      }
      
      try {
        const auction = await contract.methods.auction().call();
        const bidAmount = await contract.methods.bids(address).call();
        const hasPaidDeposit = await contract.methods.hasPaidDeposit(address).call();
        
        document.getElementById('resultAddress').textContent = address;
        document.getElementById('resultBidAmount').textContent = 
          `${web3.utils.fromWei(bidAmount, 'ether')} ETH`;
        document.getElementById('resultDepositStatus').textContent = 
          hasPaidDeposit ? '已支付' : '未支付';
        
        document.getElementById('bidInfoResult').classList.remove('hidden');
        showNotification('success', '查询成功');
      } catch (error) {
        console.error('查询出价信息失败:', error);
        showNotification('error', '查询出价信息失败: ' + error.message);
      }
    }
    
    // 验证签名
    function verifySignature() {
      showModal(
        '验证签名',
        `
          <div class="space-y-3">
            <div>
              <label class="block text-sm font-medium mb-1">消息哈希</label>
              <input id="verifyMessage" type="text" class="w-full bg-dark/80 border border-primary/40 rounded-lg px-4 py-2 focus:outline-none focus:ring-2 focus:ring-primary/50" placeholder="0x...">
            </div>
            <div>
              <label class="block text-sm font-medium mb-1">v</label>
              <input id="verifyV" type="text" class="w-full bg-dark/80 border border-primary/40 rounded-lg px-4 py-2 focus:outline-none focus:ring-2 focus:ring-primary/50" placeholder="27 或 28">
            </div>
            <div>
              <label class="block text-sm font-medium mb-1">r</label>
              <input id="verifyR" type="text" class="w-full bg-dark/80 border border-primary/40 rounded-lg px-4 py-2 focus:outline-none focus:ring-2 focus:ring-primary/50" placeholder="0x...">
            </div>
            <div>
              <label class="block text-sm font-medium mb-1">s</label>
              <input id="verifyS" type="text" class="w-full bg-dark/80 border border-primary/40 rounded-lg px-4 py-2 focus:outline-none focus:ring-2 focus:ring-primary/50" placeholder="0x...">
            </div>
            <div>
              <label class="block text-sm font-medium mb-1">签名者地址</label>
              <input id="verifySigner" type="text" class="w-full bg-dark/80 border border-primary/40 rounded-lg px-4 py-2 focus:outline-none focus:ring-2 focus:ring-primary/50" placeholder="0x...">
            </div>
          </div>
        `,
        async () => {
          const message = document.getElementById('verifyMessage').value.trim();
          const v = parseInt(document.getElementById('verifyV').value.trim());
          const r = document.getElementById('verifyR').value.trim();
          const s = document.getElementById('verifyS').value.trim();
          const signer = document.getElementById('verifySigner').value.trim();
          
          if (!message || !v || !r || !s || !signer) {
            showNotification('error', '请填写所有字段');
            return;
          }
          
          try {
            const isValid = await contract.methods.verifySignature(
              message, v, r, s, signer
            ).call();
            
            closeModal();
            showNotification(
              isValid ? 'success' : 'error',
              isValid ? '签名验证成功' : '签名验证失败'
            );
          } catch (error) {
            console.error('验证签名失败:', error);
            showNotification('error', '验证签名失败: ' + error.message);
          }
        }
      );
    }
    
    // 显示模态框
    function showModal(title, content, confirmCallback) {
      modalTitle.textContent = title;
      modalBody.innerHTML = content;
      modalConfirmBtn.onclick = () => {
        confirmCallback();
        closeModal();
      };
      
      modal.classList.remove('hidden');
      setTimeout(() => {
        modalContent.classList.remove('scale-95', 'opacity-0');
        modalContent.classList.add('scale-100', 'opacity-100');
      }, 10);
    }
    
    // 显示确认模态框
    function showConfirmationModal(title, message, confirmCallback) {
      showModal(
        title,
        `<p class="text-center">${message}</p>`,
        confirmCallback
      );
    }
    
    // 关闭模态框
    function closeModal() {
      modalContent.classList.remove('scale-100', 'opacity-100');
      modalContent.classList.add('scale-95', 'opacity-0');
      
      setTimeout(() => {
        modal.classList.add('hidden');
      }, 300);
    }
    
    // 显示通知
    function showNotification(type, message) {
      const notificationId = 'notification-' + Date.now();
      
      const notificationElement = document.createElement('div');
      notificationElement.id = notificationId;
      notificationElement.className = `p-4 rounded-lg mb-3 transform translate-y-0 opacity-100 transition-all duration-500 flex items-center`;
      
      let icon = '';
      let bgColor = '';
      
      switch (type) {
        case 'success':
          icon = 'fa-check-circle';
          bgColor = 'bg-success/20 border border-success/30';
          break;
        case 'error':
          icon = 'fa-times-circle';
          bgColor = 'bg-danger/20 border border-danger/30';
          break;
        case 'warning':
          icon = 'fa-exclamation-triangle';
          bgColor = 'bg-warning/20 border border-warning/30';
          break;
        case 'info':
          icon = 'fa-info-circle';
          bgColor = 'bg-info/20 border border-info/30';
          break;
        default:
          icon = 'fa-info-circle';
          bgColor = 'bg-info/20 border border-info/30';
      }
      
      notificationElement.className += ` ${bgColor}`;
      notificationElement.innerHTML = `
        <i class="fa ${icon} mr-3 text-xl"></i>
        <div class="flex-grow">
          <p class="font-medium">${message}</p>
        </div>
        <button onclick="document.getElementById('${notificationId}').remove()" class="ml-2 text-gray-400 hover:text-white">
          <i class="fa fa-times"></i>
        </button>
      `;
      
      notification.appendChild(notificationElement);
      
      // 自动关闭
      setTimeout(() => {
        notificationElement.classList.add('translate-y-20', 'opacity-0');
        setTimeout(() => {
          notificationElement.remove();
        }, 500);
      }, 5000);
    }
    
    // 初始化应用
    window.onload = init;
  </script>
</body>
</html>    